package trunk;

import java.awt.Point;
import java.util.ArrayList;

public class Level implements Saveable<Level> {
	private Cell[][] map;

	public Level() {
		map = new Cell[40][40];
		for (int i = 0; i < 40; i++) {
			for (int j = 0; j < 40; j++) {
				if (i != 0 && i != 39 && j != 0 && j != 39)
					if (i == 5)
						if (j == 10)
							map[i][j] = new Cell(Cell.CLOSED_DOOR_TILE);
						else
							map[i][j] = new Cell(Cell.STONE_TILE);
					else
						map[i][j] = new Cell(Cell.NORMAL_TILE);
				else
					map[i][j] = new Cell(Cell.STONE_TILE);
			}
		}
		Hero h = new Hero();
		h.setLocation(new Point(20, 20));
		h.setCurrentLevel(this);
		map[20][20].setLivingThing(h);
		Monster m = new Monster();
		m.setLocation(new Point(25, 25));
		m.setCurrentLevel(this);
		map[25][25].setLivingThing(m);
	}

	public Point findHero() {
		for (int i = 0; i < 40; i++) {
			for (int j = 0; j < 40; j++) {
				if (map[i][j].getLivingThing() != null
						&& map[i][j].getLivingThing() instanceof Hero)
					return new Point(i, j);
			}
		}
		return null;
	}

	public Point findLivingThing(LivingThing me) {
		for (int i = 0; i < 40; i++) {
			for (int j = 0; j < 40; j++) {
				if (map[i][j].getLivingThing() != null
						&& map[i][j].getLivingThing().equals(me))
					return new Point(i, j);
			}
		}
		return null;
	}

	public Hero getHero() {
		for (int i = 0; i < 40; i++) {
			for (int j = 0; j < 40; j++) {
				if (map[i][j].getLivingThing() != null
						&& map[i][j].getLivingThing() instanceof Hero)
					return (Hero) map[i][j].getLivingThing();
			}
		}
		return null;
	}

	public Cell getCell(int x, int y) {
		return map[x][y];
	}

	public int getWidth() {
		return map.length;
	}

	public int getHeight() {
		return map[0].length;
	}

	// Tells all the objects in its map that implement TimeDependent to tick
	// Currently only calls it on livingThings
	public void sendTick() {
		ArrayList<LivingThing> liveThings = new ArrayList<LivingThing>();
		for (int i = 0; i < 40; i++) {
			for (int j = 0; j < 40; j++) {
				if (map[i][j].getLivingThing() != null)
					liveThings.add(map[i][j].getLivingThing());
			}
		}
		for (LivingThing life : liveThings) {
			life.tick();
		}
	}

	public void sendTicks(int n) {
		ArrayList<LivingThing> liveThings = new ArrayList<LivingThing>();
		for (int i = 0; i < 40; i++) {
			for (int j = 0; j < 40; j++) {
				if (map[i][j].getLivingThing() != null)
					liveThings.add(map[i][j].getLivingThing());
			}
		}
		for (LivingThing life : liveThings) {
			for (int i = 0; i < n; i++)
				life.tick();
		}
	}

	@Override
	public Level load(String str) {
		return null;
	}

	@Override
	public String save() {
		String mapSave = "[";
		for (int i = 0; i < map.length; i++) {
			for (int j = 0; j < map[0].length; j++) {
				mapSave += map[i][j].save();
			}
		}
		mapSave += "]";
		return mapSave;
	}
}
